package com.mai4j.maiadmin.support.security.aop;


import org.aopalliance.intercept.MethodInvocation;
import org.jooq.tools.reflect.Reflect;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.method.HandlerMethod;

import java.lang.annotation.Annotation;

/**
 * 微信公众号请关注: 开源螺丝钉
 * <br>
 * 码云请关注: <a href="https://gitee.com/xiyoufang">https://gitee.com/xiyoufang</a>
 * <br>
 * 哔哩哔哩请关注: <a href="https://space.bilibili.com/438927834">https://space.bilibili.com/438927834</a>
 *
 * @author xiyoufang
 */
public abstract class AuthorizingAnnotationHandler {

    protected Class<? extends Annotation> annotationClass;

    public AuthorizingAnnotationHandler(Class<? extends Annotation> annotationClass) {
        setAnnotationClass(annotationClass);
    }

    public abstract void assertAuthorized(Annotation a, MethodInvocation mi) throws AccessDeniedException;

    protected void setAnnotationClass(Class<? extends Annotation> annotationClass)
            throws IllegalArgumentException {
        if (annotationClass == null) {
            String msg = "annotationClass argument cannot be null";
            throw new IllegalArgumentException(msg);
        }
        this.annotationClass = annotationClass;
    }

    public Class<? extends Annotation> getAnnotationClass() {
        return this.annotationClass;
    }

    protected static String description(MethodInvocation mi) {
        Object aThis = mi.getThis();
        if (aThis == null) return null;
        Class<?> targetClass = aThis.getClass();
        return Reflect.onClass(HandlerMethod.class).call("initDescription", targetClass, mi.getMethod()).get();
    }
}
